'use strict';
const fs = require('fs');
const path = require('path');

module.exports = (app, conf, load) => {
   if (conf.es) {
      const es = require('elasticsearch');

      try {
         app.fs = app.fs || {}
         app.fs.esclient = {}
         let esclient = conf.es.reduce((p, esmodule) => {
            load.text = ` 加载 ES ${esmodule.name}`;

            let logOptions;
            if (conf.env == 'development') {
               let filename = path.join(process.cwd(), 'logs', `elasticsearch-dev-${esmodule.name}.log`);
               let dir = path.dirname(filename);
               if (!fs.existsSync(dir)) {
                  fs.mkdirSync(dir);
               }
               logOptions = {
                  type: 'file',
                  level: 'info',
                  path: filename
               };
            } else {
               logOptions = {
                  type: 'stdio',
                  level: 'error'
               };
            }
            let client = new es.Client({
               host: esmodule.root,
               log: logOptions,
               apiVersion: '5.6'
            });

            p[esmodule.name] = client;
            p[esmodule.name].config = esmodule;
            return p;
         }, {});

         app.fs.esclient = esclient;
      } catch (error) {
         console.error(error)
         process.exit(-1);
      }
   }
};
